// 还原 less 文件

const fs = require('fs'),
  path = require('path'),
  antDesignStyleRootPath = path.resolve(process.cwd(), 'node_modules/ant-design-vue/es'),
  options = {}
// options = {
//   mainLessFile: 'framework/styles/index.less',
//   replaceVars: {
//     '@font-size-base': '1rem'
//   }
// }

function getVarsInLessFiles (filepath) {
  if (!filepath.endsWith('.less')) {
    return
  }
  const rollbackLessFilePath = filepath.replace('.less', '.less.o')
  if (fs.existsSync(rollbackLessFilePath)) {
    // 备份 less 文件
    fs.copyFileSync(rollbackLessFilePath, filepath)
  }
  const dirname = path.dirname(filepath)

  fs.readFileSync(rollbackLessFilePath, 'utf8').split('\n').map((line, index) => {
    if (/^(\s+)?@import\s+/.test(line)) {
      // 以 @import 开头的行为引入文件
      let import_file = line.match(/['"](.+)['"]/)?.[1]
      if (!import_file || import_file.startsWith('~ant-design-vue')) {
        return
      }
      if (import_file.startsWith('@')) {
        import_file = `node_modules/${import_file}`
      }
      import_file = path.join(dirname, import_file)
      return getVarsInLessFiles(path.resolve(dirname, import_file))
    }
  })
}

function getAntDesignLess (dir) {
  dir = dir || antDesignStyleRootPath
  fs.readdirSync(dir).forEach(f => {
    const stat = fs.statSync(path.join(dir, f))
    if (path.join(dir, f).indexOf('assets') !== -1) {
      return
    }
    const filepath = path.join(dir, f),
      rollbackLessFilePath = filepath.replace('.less', '.less.o')
    if (filepath.endsWith('.less') && !filepath.endsWith('.less.o')) {
      // 还原 less 文件
      fs.copyFileSync(rollbackLessFilePath, filepath)
    } else if (stat.isDirectory()) {
      getAntDesignLess(path.join(dir, f))
    }
  })
}

/**
 * 重建 less 文件
 */
module.exports = function (_options) {
  Object.assign(options, _options)

  if (!fs.existsSync(antDesignStyleRootPath)) {
    console.error('ant-design-vue 源码目录不存在: ${antDesignStyleRootPath}')
    return
  }

  getAntDesignLess()

  getVarsInLessFiles(path.join(process.cwd(), options.mainLessFile))
}